$(function () {
    'use strict';
    //定义初始化页数
    var currentPage = 1;
    var currentOrderId;
    var currentPaperOrderInfo;

    //初始化加载
    window.onload = function () {
        $.pullToRefreshTrigger(".content");
    }

    $("#picker").picker({
        toolbarTemplate: '<header class="bar bar-nav">\
       <button class="button button-link pull-right close-picker">确定</button>\
       <h1 class="title">审核状态</h1>\
       </header>',
        cols: [
            {
                textAlign: 'center',
                values: ['全部',  '待审核', '已审核'],
            }
        ],
        onClose :function (picker) {
            // 重置内容
            currentPage = 1;
            $("#page-ptr").find('.card-container').html("");
            $.pullToRefreshTrigger(".content pull-to-refresh-content native-scroll");
        }
    });

    $('#search').bind('keypress', function (event) {
        if (event.keyCode == 13) {// 回车键搜索
            // 重置内容
            currentPage = 1;
            $("#page-ptr").find('.card-container').html("");
            $.pullToRefreshTrigger(".content pull-to-refresh-content native-scroll");
        }

    });

    // 订单列表页面
    $(document).on("pageInit", "#page-ptr", function (e, id, page) {
        // 清空 详情页面
        $("#goodsContent").html("");

        //下拉刷新页面
        var $content = $(page).find(".content").on('refresh', function (e) {
            var url = "/order/paperOrder/paperOrderList?promotionType=paper&limit=5&page=" + currentPage;

            //获取keyword
            var keyword = $("#search").val();
            if (keyword) {
                url += "&keyword=" + keyword;
            }
            //获取状态
            var auditStatus =  $("#picker").val();
            if(auditStatus){
                if(auditStatus === '待审核'){
                    url += "&auditStatus=" + 0;
                }
                if(auditStatus === '已审核'){
                    url += "&auditStatus=" + 1;
                }
            }
            //ajax 请求加载数据
            $.ajax({
                type: "get",
                url: url,
                success: function (r) {
                    if (r.code === 0) {
                        if (r.page.list.length > 0) {
                            for (var i = r.page.list.length -1; i >=0 ; i--) {
                                var cardHTML = '<div class="card">' +
                                    '<div class="card-header">' + r.page.list[i].orderId + '<h5>'+r.page.list[i].payStatusText+'</h5></div>' +
                                    '<div class="card-content">' +
                                    '<div class="card-content-inner">' +
                                    '<div class="row">' +
                                    '<div class="col-40">' + r.page.list[i].memberName + '</div>' +
                                    '<div class="col-40">￥' + r.page.list[i].totalAmount + '</div>' +
                                    '<div class="col-20"><a  href="javascript:;" orderId="' + r.page.list[i].orderId + '"  class="button look">查看</a></div>' +
                                    '</div>' +
                                    '<div class="row">' +
                                    '<div class="col-60">' + r.page.list[i].createtime + '</div>' +
                                    '</div>'+
                                    '</div>' +
                                    '</div>' +
                                    '</div>';
                                $content.find('.card-container').prepend(cardHTML);
                            }
                            // 加载完毕需要重置
                            $.pullToRefreshDone($content);
                            currentPage += 1;

                        } else {
                            $.toast('暂无新订单！');
                            // 加载完毕需要重置
                            $.pullToRefreshDone($content);
                        }
                        // 加载成功
                    } else {
                        $.alert(r.msg);
                        // 加载完毕需要重置
                        $.pullToRefreshDone($content);
                    }
                }
            });
        });
    });
    //订单详情页面
    $(document).on("pageInit", "#page-detail", function (e, id, page) {
        if (currentOrderId) {// 获取当前订单id
            //ajax 请求
            $.ajax({
                type: "get",
                url: "/order/paperOrder/info/" + currentOrderId,
                success: function (r) {
                    if (r.code === 0) {
                        // 加载成功 获取后台数据
                        currentPaperOrderInfo = r.paperOrderInfo;
                        var orderItemList = r.orderItemList;

                        //1.首先赋值订单信息
                        $('#orderId').html(currentPaperOrderInfo.orderId);
                        $('#createtime').html(currentPaperOrderInfo.createtime);

                        //循环订单明细
                        var totalAmount = 0;
                        for (var i = 0; i < orderItemList.length; i++) {
                            var currentItem = orderItemList[i];
                            totalAmount += currentItem.amount;
                            var htmlCodes = [
                                '<div class="card" style="margin: 0" name="goodsCard">',
                                '                            <div class="card-content ">',
                                '                                <div class="list-block">',
                                '                                    <ul>',
                                '                                        <li class="item-content" style="padding-left: 0">',
                                '                                            <div class="item-media"><i class="icon icon-f7"></i></div>',
                                '                                            <div class="item-inner">',
                                '                                                <div class="item-title">货号</div>',
                                '                                                <div class="item-after"> ' +
                                '                                                    <input type="text" value="' + currentItem.goodsId + '" style="text-align: right;width:6rem;" readonly>',
                                '                                               </div>',
                                '                                            </div>',
                                '                                        </li>',
                                '                                        <li class="item-content" style="padding-left: 0">',
                                '                                            <div class="item-media"><i class="icon icon-f7"></i></div>',
                                '                                            <div class="item-inner">',
                                '                                                <div class="item-title">商品名称</div>',
                                '                                                <div class="item-after">' + currentItem.name + '</div>',
                                '                                            </div>',
                                '                                        </li>',
                                '                                        <li class="item-content" style="padding-left: 0">',
                                '                                            <div class="item-inner">',
                                '                                                <textarea readonly style="margin-left: .6rem;height: 3rem" >' + currentItem.addon + '</textarea>',
                                '                                            </div>',
                                '                                        </li>',
                                '                                        <li class="item-content" style="padding-left: 0">',
                                '                                            <div class="item-media"><i class="icon icon-f7"></i></div>',
                                '                                            <div class="item-inner">',
                                '                                                <div class="item-title">商品总额</div>',
                                '                                                <div class="item-after">',
                                '                                                    <div class="item-input">',
                                '                                                        <input readonly type="text" index=' + i + ' value="' + currentItem.amount + '" name="amount" style="text-align: right;width:6rem;" placeholder="商品总额">',
                                '                                                    </div>',
                                '                                                </div>',
                                '                                            </div>',
                                '                                        </li>',
                                '                                        <li class="item-content" style="padding-left: 0">',
                                '                                            <div class="item-media"><i class="icon icon-f7"></i></div>',
                                '                                            <div class="item-inner">',
                                '                                                <div class="item-title">购买数量</div>',
                                '                                                <div class="item-after">',
                                '                                                    <div class="item-input">',
                                '                                                        <input type="number" index=' + i + ' value="' + currentItem.nums + '" name="nums" style="text-align: right;width:6rem;" placeholder="购买数量">',
                                '                                                    </div>',
                                '                                                </div>',
                                '                                            </div>',
                                '                                        </li>'
                            ].join("");
                            /*------------------分割线--------------------*/
                            // 逻辑判断 增加 li
                            // 1. 先判断 是大纸或者复印纸
                            var g = currentItem.addon.match(/[0-9]*?(?=g)/)[0];
                            if (currentItem.goodsType == 'paper') { //大纸
                                // 判断是吨价 还是令价格
                                if (currentItem.paperUnit == 'ton') {// 吨价
                                    // 吨价直接显示 修改
                                    var addonObject = {};
                                    addonObject.paperWidth = currentItem.paperSize;
                                    addonObject.paperWeight = g;
                                    addonObject.goodsType = currentItem.goodsType;
                                    addonObject.paperUnit = currentItem.paperUnit;
                                    addonObject.itemId = currentItem.itemId;

                                    var liTon = [
                                        '                                        <li class="item-content" style="padding-left: 0">',
                                        '                                            <div class="item-media"><i class="icon icon-f7"></i></div>',
                                        '                                            <div class="item-inner">',
                                        '                                                <div class="item-title">吨价</div>',
                                        '                                                <div class="item-after">',
                                        '                                                    <div class="item-input">',
                                        '                                                        <input  type="number" addonObject=' + JSON.stringify(addonObject) + ' index=' + i + ' value="' + currentItem.price + '" name="priceTon" style="text-align: right;width:6rem;" placeholder="吨价">',
                                        '                                                    </div>',
                                        '                                                </div>',
                                        '                                            </div>',
                                        '                                        </li>'
                                    ].join("");

                                    htmlCodes += liTon;
                                } else if (currentItem.paperUnit == 'ream') {// 令价
                                    var addonObject = {};
                                    addonObject.paperLen = currentItem.paperSize.split(',')[0];
                                    addonObject.paperWidth = currentItem.paperSize.split(',')[1];
                                    addonObject.paperWeight = g;
                                    addonObject.goodsType = currentItem.goodsType;
                                    addonObject.paperUnit = currentItem.paperUnit;
                                    addonObject.itemId = currentItem.itemId;
                                    var tonPrice = tonsOrReam(addonObject, currentItem.price, 0);

                                    var liReam = [
                                        '                                        <li class="item-content" style="padding-left: 0">',
                                        '                                            <div class="item-media"><i class="icon icon-f7"></i></div>',
                                        '                                            <div class="item-inner">',
                                        '                                                <div class="item-title">吨价</div>',
                                        '                                                <div class="item-after">',
                                        '                                                    <div class="item-input">',
                                        '                                                        <input type="number" addonObject=' + JSON.stringify(addonObject) + ' index=' + i + ' value="' + tonPrice + '" name="priceTon" style="text-align: right;width:6rem;" placeholder="吨价">',
                                        '                                                    </div>',
                                        '                                                </div>',
                                        '                                            </div>',
                                        '                                        </li>',
                                        '                                        <li class="item-content" style="padding-left: 0">',
                                        '                                            <div class="item-media"><i class="icon icon-f7"></i></div>',
                                        '                                            <div class="item-inner">',
                                        '                                                <div class="item-title">令价</div>',
                                        '                                                <div class="item-after">',
                                        '                                                    <div class="item-input">',
                                        '                                                        <input type="number" addonObject=' + JSON.stringify(addonObject) + ' index=' + i + ' value="' + currentItem.price + '" name="priceReam" style="text-align: right;width:6rem;" placeholder="令价">',
                                        '                                                    </div>',
                                        '                                                </div>',
                                        '                                            </div>',
                                        '                                        </li>'
                                    ].join("");

                                    htmlCodes += liReam;
                                }

                            } else if (currentItem.goodsType == 'copy') { // 复印纸
                                // 复印纸 价格一定为吨价 paperUnit 为none
                                if (currentItem.paperUnit == 'none') {
                                    var addonObject = {};
                                    // 克重、包数、尺寸
                                    var p = currentItem.addon.match(/[0-9]+[包]/)[0].match(/\d/)[0];
                                    var ad = currentItem.addon.match(/([AB][345])|(\d*?(?=K)+K)/)[0];
                                    var size = 0;
                                    if (ad == 'A3') {
                                        size = 420 * 297
                                    } else if (ad == 'A4') {
                                        size = 210 * 297
                                    } else if (ad == 'B4') {
                                        size = 257 * 364
                                    } else if (ad == 'B5') {
                                        size = 182 * 257
                                    } else if (ad == '16K') {
                                        size = 270 * 195
                                    } else if (ad == '8K') {
                                        size = 270 * 390
                                    }
                                    addonObject.paperWeight = g;
                                    addonObject.paperPakg = p;
                                    addonObject.paperCopySize = size;
                                    addonObject.goodsType = currentItem.goodsType;
                                    addonObject.paperUnit = currentItem.paperUnit;
                                    addonObject.itemId = currentItem.itemId;

                                    var tonPrice = tonsOrXj(addonObject, currentItem.price, 1);

                                    var liCopy = [
                                        '                                        <li class="item-content" style="padding-left: 0">',
                                        '                                            <div class="item-media"><i class="icon icon-f7"></i></div>',
                                        '                                            <div class="item-inner">',
                                        '                                                <div class="item-title">吨价</div>',
                                        '                                                <div class="item-after">',
                                        '                                                    <div class="item-input">',
                                        '                                                        <input type="number" addonObject=' + JSON.stringify(addonObject) + ' index=' + i + ' value="' + tonPrice + '" name="priceTon" style="text-align: right;width:6rem;" placeholder="吨价">',
                                        '                                                    </div>',
                                        '                                                </div>',
                                        '                                            </div>',
                                        '                                        </li>',
                                        '                                        <li class="item-content" style="padding-left: 0">',
                                        '                                            <div class="item-media"><i class="icon icon-f7"></i></div>',
                                        '                                            <div class="item-inner">',
                                        '                                                <div class="item-title">箱价</div>',
                                        '                                                <div class="item-after">',
                                        '                                                    <div class="item-input">',
                                        '                                                        <input type="number" addonObject=' + JSON.stringify(addonObject) + ' index=' + i + ' value="' + currentItem.price + '" name="priceNone" style="text-align: right;width:6rem;" placeholder="箱价">',
                                        '                                                    </div>',
                                        '                                                </div>',
                                        '                                            </div>',
                                        '                                        </li>'
                                    ].join("");

                                    htmlCodes += liCopy;
                                }

                            }
                            htmlCodes += '</ul></div></div></div>';


                            $("#goodsContent").append(htmlCodes);

                        }

                        $('#totalAmount').html(totalAmount);


                    } else {
                        $.alert(r.msg);
                    }
                }
            });
        }
        //监听 input框变化
        $(page).on("change", "input[type='number']", function () {
            var value = this.value;
            if (isNaN(value)) { // 非数字
                this.value = 0;
                $.toast("请填写正确数字!");
                return;
            }
            var name = this.name; //取出 name
            var index = $(this).attr('index'); // 取出下标

            var addonObject = JSON.parse($(this).attr('addonObject'));

            if (name == 'priceTon') { //吨价发生变化
                // 重算令价与箱价
                if (addonObject.paperUnit == 'ream') { //有令价 则计算令价
                    var reamPrice = tonsOrReam(addonObject, value, 1);
                    // 赋值令价
                    $(page).find("input[name='priceReam'][index='" + index + "']").val(reamPrice);
                }

                if (addonObject.goodsType == 'copy') { //复印纸 则计算箱价
                    var priceNone = tonsOrXj(addonObject, value, 0);
                    // 赋值箱价
                    $(page).find("input[name='priceNone'][index='" + index + "']").val(priceNone);

                }

            } else if (name == 'priceReam') { //令价发生变化
                // 重算吨价
                var tonsPrice = tonsOrReam(addonObject, value, 0);
                // 赋值吨价
                $(page).find("input[name='priceTon'][index='" + index + "']").val(tonsPrice);

            } else if (name == 'priceNone') { // 箱价发生变化
                // 重算吨价
                var tonsPrice = tonsOrXj(addonObject, value, 1);
                $(page).find("input[name='priceTon'][index='" + index + "']").val(tonsPrice);

            }
            // 遍历所有card 重算 amount 和小计
            var totalAmount = 0;
            $(page).find("div[name='goodsCard']").each(function (index, element) {
                // 获取数量 与吨价 计算amount
                var nums = $(element).find('input[name=nums]').val();
                // 获取对象信息
                var addonObject = JSON.parse($(element).find('input[name=priceTon]').attr('addonObject'));
                // 判断价格方式
                var price = 0;
                if (addonObject.paperUnit == 'ream') { // 以令价进行计算
                    price = $(element).find('input[name=priceReam]').val();
                } else if (addonObject.paperUnit == 'ton') { // 吨价运算
                    price = $(element).find('input[name=priceTon]').val();
                } else if (addonObject.paperUnit == 'none' && addonObject.goodsType == 'copy') {
                    // 复印纸 以吨价运算
                    price = $(element).find('input[name=priceTon]').val();
                }
                // 计算总金额
                var amount = String(nums * price).replace(/^(.*\..{2}).*$/, "$1");
                // 赋值总金额
                $(element).find('input[name=amount]').val(amount);
                totalAmount = totalAmount + Number(amount);
            })
            // 赋值小计 + 优惠金额 + 运费金额
            var discount = $(page).find("input[name='discount']").val();
            var costFreight = $(page).find("input[name='costFreight']").val();
            totalAmount = totalAmount + Number(discount) + Number(costFreight);
            totalAmount = String(totalAmount).replace(/^(.*\..{2}).*$/, "$1");
            $("#totalAmount").html(totalAmount);
            $.toast("合计价格:" + totalAmount);

        });

    });

    // 点击查看事件
    $(document).on('click', '.look ', function () {
        var orderId = $(this).attr("orderId");
        currentOrderId = orderId;
        $.router.load('#page-detail', true);
    });

    //审核事件
    $(document).on('click', '.check ', function () {
        //判断状态
        if (currentPaperOrderInfo.status != 'active' || currentPaperOrderInfo.payStatus != '6'){
            $.alert("当前订单状态不支持审核 !");
            return;
        }


        // 主表信息
        var paperOrderInfo = {};
        // 获取订单ID
        var orderId = $("#orderId").html();
        paperOrderInfo.orderId = orderId;

        var discount = $("#page-detail").find("input[name='discount']").val();
        var costFreight = $("#page-detail").find("input[name='costFreight']").val();
        var payableAmount = $("#totalAmount").html();
        paperOrderInfo.discount = discount;
        paperOrderInfo.costFreight = costFreight;
        paperOrderInfo.payableAmount = payableAmount;

        // 获取所有goodsCards  组装 orderItem
        var orderItem = [];
        $("#page-detail").find("div[name='goodsCard']").each(function (index, element) {
            var order = {};
            // 获取数量 与吨价
            var nums = $(element).find('input[name=nums]').val();
            order.nums = nums;
            // 获取对象信息
            var addonObject = JSON.parse($(element).find('input[name=priceTon]').attr('addonObject'));

            order.itemId = addonObject.itemId;
            // 判断价格方式
            var price = 0;
            if (addonObject.paperUnit == 'ream') { // 以令价进行计算
                price = $(element).find('input[name=priceReam]').val();
            } else if (addonObject.paperUnit == 'ton') { // 吨价运算
                price = $(element).find('input[name=priceTon]').val();
            } else if (addonObject.paperUnit == 'none' && addonObject.goodsType == 'copy') {
                // 复印纸 以吨价运算
                price = $(element).find('input[name=priceTon]').val();
            }
            order.price = price;

            // 获取总金额
            var amount = $(element).find('input[name=amount]').val();
            order.amount = amount;
            orderItem.push(order);
        });
        // 提交后台参数
        var param = {orderInfo: JSON.stringify(paperOrderInfo), orderItem: JSON.stringify(orderItem)};
        // ajax 提交数据
        $.ajax({
            type: "POST",
            url: "/order/paperOrder/paperAudit",
            contentType: "application/json",
            data: JSON.stringify(param),
            success: function (r) {
                if (r.code === 0) {
                    $.toast("审核成功");
                } else {
                    $.alert(r.msg);
                }
            }
        });
    });

    /**
     * 吨价与令价转换公式
     * @param addon 规格
     * @param price 价格
     * @param flag 0令价转吨价 1 吨价转令价
     */
    function tonsOrReam(addon, price, flag) {
        //解析规格
        var g = addon.paperWeight; // 克重
        var lo = addon.paperLen; // 长
        var w = addon.paperWidth; // 宽
        if (flag == 0) {//令价转吨价
            // 吨价 = 令价 * ( 1000 * 1000 * 1000 * 2 ) /(长*宽*克重)
            var tonPrice = price * (1000 * 1000 * 1000 * 2) / (g * w * lo); // 吨价
            if (isNaN(Number(tonPrice))) {
                tonPrice = 0
            }
            return String(tonPrice).replace(/^(.*\..{4}).*$/, "$1");

        }
        if (flag == 1) {//吨价 转令价
            // 价价 = 吨价 * (长*宽*克重) /( 1000 * 1000 * 1000 * 2 )
            var reamPrice = price * (g * w * lo) / (1000 * 1000 * 1000 * 2); // 令价
            if (isNaN(Number(reamPrice))) {
                reamPrice = 0
            }
            return String(reamPrice).replace(/^(.*\..{4}).*$/, "$1");
        }
    }

    /**
     * 吨价与箱价转换公式
     * @param addon 规格
     * @param price 价格
     * @param flag 0 吨价转箱价  1箱价转吨价
     */
    function tonsOrXj(addon, price, flag) {
        //解析规格
        var g = addon.paperWeight; // 克重
        var pakg = addon.paperPakg; // 包数
        var size = addon.paperCopySize; // 尺寸
        if (flag == 0) { //吨价转箱价
            //箱价 = 吨价 * 克重 * 包数 * 尺寸 / (1000*1000*1000*2)
            var xjPrice = price * (g * pakg * size) / (1000 * 1000 * 1000 * 2); // 箱价
            if (isNaN(Number(xjPrice))) {
                xjPrice = 0
            }
            return String(xjPrice).replace(/^(.*\..{4}).*$/, "$1");

        }
        if (flag == 1) {//箱价转吨价
            //顿价 = 箱价 * (1000*1000*1000*2) /(克重 * 包数 * 尺寸)
            var tonPrice = price * (1000 * 1000 * 1000 * 2) / (g * pakg * size); // 顿价
            if (isNaN(Number(tonPrice))) {
                tonPrice = 0
            }
            return String(tonPrice).replace(/^(.*\..{4}).*$/, "$1");

        }

    }

    $.init();
});
